import { News } from './../../domain/news';
import { NewsService } from './../../service/news.service';
import { ActivatedRoute } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { EditorService } from '../../component/editor/editor.service';
import { Toastr } from '../../common/toastr';
import { NavbarService } from '../../component/navbar/navbar.service';

@Component({
    moduleId: module.id,
    templateUrl: 'newsEdit.component.html'
})
export class NewsEditComponent implements OnInit {
    private title: string = "新闻编辑";
    private subTitle: string = "编辑或修改新闻";
    private news: News = new News();

    constructor(
        private route: ActivatedRoute,
        private newsSvr: NewsService,
        private editorSvr: EditorService
    ) { }

    async ngOnInit() {
        try {
            this.editorSvr.UploadImage = this.uploadNewsContentImage.bind(this);
            let id = +this.route.snapshot.params['id'];
            if (id)
                this.news = await this.newsSvr.GetNewsInfo(id);

            this.editorSvr.SetHtmlCode(this.news.content);
        } catch (error) {
            Toastr.Error(error);
        }
    }

    async uploadNewsImage() {
        try {
            let fileInput: any = (<any>document.getElementById("imgfile")).files[0];
            this.news.cover = await this.newsSvr.UploadNewsImage(fileInput);
            Toastr.Success("封面图上传成功！");
        } catch (error) {
            Toastr.Error(error);
        }
    }

    async okBtn() {
        this.news.content = this.editorSvr.GetHtmlCode();
        try {
            await this.newsSvr.SaveNews(this.news);
            NavbarService.Current.Navigate(['/main/news']);
        } catch (error) {
            Toastr.Error(error);
        }
    }

    async uploadNewsContentImage(files: any) {
        try {
            let imageUrl = await this.newsSvr.UploadNewsImage(files);
            this.editorSvr.InsertImage(imageUrl);

        } catch (error) {
            Toastr.Error(error);
        }
    }
}